<script setup lang="ts">
import {DrawerProps, ElMessageBox, TabsInstance} from "element-plus";
import * as echarts from 'echarts';
import {ref, onMounted, nextTick, computed, reactive, watch, onBeforeUnmount, watchEffect} from 'vue';
import cj from '@/components/cj.vue';
import type { TabsPaneContext } from 'element-plus'
const tabPosition = ref<TabsInstance['tabPosition']>('left')
const tableDatas =ref([])
let total = ref(0)
let pageSize = ref(25)
let currentPage = ref(1)
const editableTabsValue = ref('1')
const id = ref('')
const handleCurrentChange = (e) => {
  currentPage.value = e
  // getData()
}
const handleSizeChange = (e)=>{
  pageSize.value = e
  // getData()
}
const editableTabs = ref([])
const optionbj = ref([])
const options = ref([])
const propst = {
  label:"name",
  value:"id"
}
const propst1 = {
  label:"title",
  value:"id"
}
import * as Api from '@/api/class'
//----------------------------------------数据分析--------------------------
const hiArray = ref([])
const qtypeRange = [0, 1, 2, 3, 4, 5]; // 假设 qtype 范围是 0-5
const gethi = async ()=> {
  let result = await Api.hilist()
  options.value = result.data
  const data =result.data
  fw.value = options.value.length > 0 ? options.value[0].id : null;
  if (Array.isArray(data)) {
    data.forEach(item => {
      if (item.id !== undefined) {
        hiArray.value.push(item.id); // 使用.value来访问和修改ref的值
      }
    });
  } else {
    // 如果响应数据不是数组，但有一个id属性，您也可以直接添加它（但这里我们假设它是数组）
    console.warn('Expected an array of items, but got something else.', data);
  }
}
const fw = ref()
const ci = ref();
const results = ref([]);

// 独立的分数ref变量
const score0 = ref([]);
const score1 = ref([]);
const score2 = ref([]);
const score3 = ref([]);
const score4 = ref([]);
const score5 = ref([]);

const fetchScore = async (homeworkId, qtype, classId) => {
  try {
    const response = await Api.typeAverage({
      homeworkId,
      classId,
      qtype,
      type: 2,
    });

    return {
      qtype,
      score: response.data,
      homeworkId,
      classId,
    };
  } catch (error) {
    console.error(`获取分数失败 homeworkId:${homeworkId}, qtype:${qtype}`, error);
    return null;
  }
};

const resetScores = () => {
  results.value = [];
  score0.value = [];
  score1.value = [];
  score2.value = [];
  score3.value = [];
  score4.value = [];
  score5.value = [];
};

const updateScore = (qtype, score) => {
  switch(qtype) {
    case 0: score0.value.push(score); break;
    case 1: score1.value.push(score); break;
    case 2: score2.value.push(score); break;
    case 3: score3.value.push(score); break;
    case 4: score4.value.push(score); break;
    case 5: score5.value.push(score); break;
  }
};

const fetchAndLogResults = async (homeworkId, qtype, classId) => {
  try {
    const result = await fetchScore(homeworkId, qtype, classId);
    if (result) {
      results.value.push(result);
      updateScore(result.qtype, result.score);
    }
  } catch (error) {
    console.error('获取分数失败:', error);
  }
};
const homeworkIds = hiArray.value
const score1s = [0,365,385,405,425,445,465]
const score2s = [365,385,405,425,445,465,750]
const people = ref([]);
// 用于存储每个班级的结果
const classResults = ref([]);

// 发送请求的函数

// 生成分数段标签
const getRangeLabel = (index) => {
  if (index === 0) return `<${score2s[0]}`;
  if (index === score1s.length - 1) return `>${score1s[score1s.length - 1]}`;
  return `${score1s[index]}-${score2s[index]}`;
};

// 发送请求的函数
const sendRequests = async (classId, className) => { // 添加className参数
  const classResult = {
    name: className, // 使用班级名称
    ranges: score1s.map((_, index) => getRangeLabel(index)),
    counts: Array(score1s.length).fill(0) // 初始化计数数组
  };

  if (score1s.length === score2s.length) {
    for (let i = 0; i < score1s.length; i++) {
      try {
        const response = await Api.rank({
          "score1": score1s[i],
          "score2": score2s[i],
          "type": 2,
          "homeworkId": fw.value,
          "classId": classId
        });

        console.log(`班级 ${classId} 请求成功:`, response.data);
        // 假设response.data是人数，直接存入对应位置
        classResult.counts[i] = response.data || 0;

      } catch (error) {
        console.error(`班级 ${classId} 请求失败:`, error);
        classResult.counts[i] = 0; // 错误时设为0
      }
    }
  } else {
    console.error('score1s 和 score2s 数组长度不匹配');
    return null;
  }

  return classResult;
};

// 处理所有班级的函数
const processAllClasses = async () => {
  classResults.value = []; // 清空之前的结果

  try {
    // 使用Promise.all并行处理所有班级
    const promises = classes.value.map(cl =>
        sendRequests(cl.id, cl.name) // 假设班级名称格式
    );
    const results = await Promise.all(promises);

    // 过滤掉可能的null结果
    classResults.value = results.filter(result => result !== null);

    console.log('所有班级处理完成:', classResults.value);

  } catch (error) {
    console.error('处理班级时出错:', error);
  }
};

const classIds = ref([]);
const classes =ref([]);
const getclass = async () => {
  let result = await Api.listclass();
  const classes = result.data;

  // 清空现有的数组
  classIds.value = [];

  // 遍历响应数据并将班级ID添加到数组中
  for (const classInfo of classes) {
    classIds.value.push(classInfo.id);
  }

  console.log('班级ID已添加到数组:', classIds.value);
};

const tableData = ref([])
const paimin = async  ()=>{
  try {
    // 首先获取所有班级的学生数据
    const studentPromises = classIds.value.map(classId => Api.findstu(classId).then(result => {
      if (result.code === 200) {
        return result.data; // 假设result.data是学生数组
      } else {
        throw new Error(`请求班级ID ${classId} 失败，状态码：${result.code}`);
      }
    }));

    const allStudents = await Promise.all(studentPromises);
    const flatStudents = allStudents.flat(); // 将二维数组转换为一维数组

    // 创建一个数组来存储带有成绩的学生数据
    const studentsWithScores = [];

    // 对每个学生获取成绩，并添加到studentsWithScores数组中
    for (const student of flatStudents) {
      try {
        const scoreResult = await Api.score({
          "stuId": student.id,
          "homeworkId": fw.value
        }); // 假设Api有findscore方法来获取成绩
        if (scoreResult.code === 200) {
          studentsWithScores.push({ ...student, score: scoreResult.data }); // 假设scoreResult.data是成绩
        } else {
          // 处理获取成绩失败的情况
          console.error(`获取学生ID ${student.id} 的成绩失败，状态码：${scoreResult.code}`);
          // 可以选择添加没有成绩的学生数据，或者跳过该学生
          studentsWithScores.push({ ...student, score: null }); // 这里选择添加但没有成绩
        }
      } catch (scoreError) {
        // 处理获取成绩时发生的任何错误
        console.error(`获取学生ID ${student.id} 的成绩时发生错误：`, scoreError);
        studentsWithScores.push({ ...student, score: null }); // 添加但没有成绩
      }
    }
    // 更新表格数据
    tableData.value = studentsWithScores;
  } catch (error) {
    console.error('请求过程中发生错误：', error);
    // 在这里添加额外的错误处理逻辑
  }
}








// ----------------------------------------------图表
const chartDom = ref(null); // 折线图DOM
const chartDomfw = ref(null); // 柱状图DOM

// 图表实例
let lineChart = null; // 折线图实例
let barChart = null;  // 柱状图实例

// 图表配置
// 折线图配置
const getChartOption = () => ({
  title: {
    text: '专项分析:'
  },
  tooltip: {
    trigger: 'axis'
  },
  legend: {
    data: ['写作', '听力', '选词填空', '长篇阅读', '仔细阅读', '翻译']
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  toolbox: {
    feature: {
      saveAsImage: {}
    }
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: ['第一次模考', '第二次模考', '第三次模考', '第四次模考', '第五次模考']
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      name: '写作',
      type: 'line',
      data: score0.value,
    },
    {
      name: '听力',
      type: 'line',
      data: score1.value,
    },
    {
      name: '选词填空',
      type: 'line',
      data: score2.value,
    },
    {
      name: '长篇阅读',
      type: 'line',
      data: score3.value,
    },
    {
      name: '仔细阅读',
      type: 'line',
      data: score4.value,
    },
    {
      name: '翻译',
      type: 'line',
      data: score5.value,
    }
  ]
});

// 柱状图配置
const getBarOption = () => ({
  title: {
    text: '分数段分布(人):'
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    }
  },
  legend: {
    data: classResults.value.map(cls => cls.name)
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    data: classResults.value[0]?.ranges || []
  },
  yAxis: {
    type: 'value'
  },
  series: classResults.value.map(cls => ({
    name: cls.name,
    type: 'bar',
    data: cls.counts,
    // itemStyle: {
    //   color: cls.name.includes('1)班') ? '#5470C6' : '#91CC75'
    // }
  }))
});



//--------------------------------------------------------------------------
  onMounted(async () => {
    const id = JSON.parse(localStorage.getItem("id"))
    let result = await Api.findclass(id);
    if (result.code === 200) {
      // 假设 editableTabs 和 optionbj 都是 Vue 的 ref 变量
      editableTabs.value = result.data;
      optionbj.value = result.data;
      classes.value = result.data;
      console.log(optionbj.value);
      ci.value = optionbj.value.length > 0 ? optionbj.value[0].id : null;
    }
    await getclass()
    await gethi()
    await paimin()
    await processAllClasses()
    // 侦听 selectedClass 的变化
    watch(ci, async (newClassId) => {
      if (newClassId !== null) {
        console.log(`检测到 classId 变化: ${newClassId}`);

        // 重置所有数据
        resetScores();

        try {
          // 并行请求优化
          const requests = [];
          for (const qtype of qtypeRange) {
            for (const homeworkId of homeworkIds) {
              requests.push(fetchAndLogResults(homeworkId, qtype, newClassId));
            }
          }

          await Promise.all(requests);

          console.log('所有分数已更新:', {
            score0: score0.value,
            score1: score1.value,
            score2: score2.value,
            score3: score3.value,
            score4: score4.value,
            score5: score5.value
          });

        } catch (error) {
          console.error('获取分数过程中出错:', error);
        }

      } else {
        resetScores();
        console.log('classId 为 null，已重置所有分数');
      }
    }, { immediate: true });
    //
    // await sendRequests(ci.value)
    var myChart1 = echarts.init(document.getElementById('leida'));
    let option1 = {
      title: {
        text: '平均能力:'
      },
      tooltip: {
        trigger: 'item', // 触发类型为 item
        formatter: function (params) {
          var indicatorName = params.name;
          var value = params.value[0]; // 雷达图的数据是数组形式，取第一个值
          return indicatorName + ': ' + value;
        }
      },
      legend: {
        data: ['23大数据(1)班', '23大数据(2)班']
      },
      radar: {
        // shape: 'circle',
        indicator: [
          {name: '写作', max: 106.5},
          {name: '听力', max: 248.5},
          {name: '选词填空', max: 35.5},
          {name: '长篇阅读', max: 71},
          {name: '仔细阅读', max: 142},
          {name: '翻译', max: 106.5}
        ]
      },
      series: [
        {
          name: 'Budget vs spending',
          type: 'radar',
          data: [
            {
              value: [51.2, 172.4, 24.5, 40.5, 101, 59.7],
              name: '23大数据(1)班'
            },
            {
              value: [64.8, 156.1, 26.4, 28.7, 103, 68.5],
              name: '23大数据(2)班'
            },
          ]
        }
      ]
    };
    myChart1.setOption(option1);
    if (chartDom.value) {
      lineChart = echarts.init(chartDom.value);
      watchEffect(() => {
        lineChart.setOption(getChartOption());
      });
    }

    // 初始化柱状图
    if (chartDomfw.value) {
      barChart = echarts.init(chartDomfw.value);
      watchEffect(() => {
        barChart.setOption(getBarOption());
      });
    }
  })

// 销毁图表
onBeforeUnmount(() => {
  lineChart?.dispose();
  barChart?.dispose();
});


const getData = async (tabname) => {
    let result = await Api.pagestu(tabname, {
      "currentPage": currentPage.value,
      "pageSize": pageSize.value,
      "classId": tabname
    })
    if (result.code === 200) {
      tableDatas.value = result.data.rows
      total.value = result.data.total
    }
  }
  const handleClick = (tab: TabsPaneContext, event: Event) => {
    console.log(tab.paneName)
    getData(tab.paneName)
  }

  interface User {
    date: string
    name: string
    address: string
  }
//   const expandedRowKeys = ref([]);
// // 处理展开变化
//   const handleExpandChange = (row, expandedRows) => {
//     // 清空之前的展开行
//     expandedRowKeys.value = [];
//
//     // 如果当前行在展开的行中，则添加到展开行键数组中
//     if (expandedRows.includes(row)) {
//       expandedRowKeys.value.push(row.id);
//     }
//   };
const expandedRowKeys = ref([]);
const currentStudentId = ref('');
const cjRef = ref(null); // 子组件引用

// 展开行变化时触发
const handleExpandChange = (row, expandedRows) => {
  if (expandedRows.length > 0) {
    currentStudentId.value = row.id
  }
}
// 刷新当前学生成绩
const refreshScores = () => {
  cjRef.value?.refresh()
}
</script>

<template>
  <el-tabs
      v-model="editableTabsValue"
      class="demo-tabs"
      :tab-position="tabPosition"
      style="height: 100%"
      @tab-click="handleClick"
  >
    <el-tab-pane label="分析" name="1">
      <el-scrollbar height="900px">
        <div style="display: flex;flex-direction: column;height: 100%;width: 100%">
          <div style="height: 400px;width: 100%;margin-top: 20px;display: flex;justify-content: space-around;">
            <div>
              <div style="width: 700px;height: 40px;">
                <el-select-v2
                    v-model="ci"
                    size="small"
                    filterable
                    :options="optionbj"
                    :props="propst"
                    placeholder="班级:"
                    style="width: 150px;margin-right: 20px;margin-bottom: 18px"
                />
              </div>
              <div ref="chartDom" style="width: 700px;height:300px"> </div>
            </div>
            <div id="leida" style="width: 600px;height: 430px;"> </div>
          </div>
          <div style="height:500px;width: 100%;margin-top: 20px;display: flex;justify-content: space-around;border-top: #6b778c 1px solid">
            <div>
              <div style="width: 100px;height: 40px;">
                <el-select-v2
                    v-model="fw"
                    size="small"
                    filterable
                    :options="options"
                    :props="propst1"
                    placeholder="请选择:"
                    style="width: 150px;margin-right: 20px;margin-bottom: 14px"
                />
              </div>
              <div  ref="chartDomfw" style="width:700px;height:300px"> </div>
            </div>
              <el-table :data="tableData" style="width: 600px;margin-top: 20px;height: 300px;margin-top: 20px">
                <el-table-column label="排名" type="index" width="80"/>
                <el-table-column label="学号" prop="id" />
                <el-table-column label="姓名" prop="name" />
                <el-table-column label="成绩" prop="score">
                  <template v-slot="scope">
                    <span v-if="scope.row.score === null">0</span>
                    <span v-else>{{ scope.row.score }}</span>
                  </template>
                </el-table-column>
              </el-table>
          </div>
          </div>
      </el-scrollbar>
    </el-tab-pane>

<!---班级信息------>
    <el-tab-pane
        v-for="item in editableTabs"
        :key="item.id"
        :label="item.name"
        :name="item.id"
    >
      <el-row style="margin-top: 20px">
        <el-col :span="10">
          <el-input
              style="width: 200px;padding-left: 5px;border-radius: 20px ;margin-right: 5px;"
              placeholder="请输入学生姓名"
          />
          <el-button style="border: solid 1px #4285F4;border-radius: 20px;width: 20px;color: #4285F4;background-color:rgb(216.8, 235.6, 255);">
            <el-icon class="el-icon--right"><el-icon><Search /></el-icon></el-icon>
          </el-button>
        </el-col>
        <el-col :span="10">
        </el-col>
      </el-row>
      <div style="height: 88%;width: 100%;margin-top: 20px">
        <el-table
            :data="tableDatas"
            :default-sort="{ prop: 'date', order: 'descending' }"
            style="width: 100%;height: 95%"
            row-key="id"
            :expand-row-keys="expandedRowKeys"
            @expand-change="handleExpandChange"
        >
          <el-table-column fixed type="index" label="编号" width="120" />
          <el-table-column prop="id" label="学号" width="120" />
          <el-table-column prop="name" label="姓名" width="180" />
          <el-table-column prop="idCard" label="身份证号码" width="180" />
          <el-table-column prop="gender" label="性别" width="180" />
          <el-table-column  prop="teachId" label="联系电话" width="180" />
          <el-table-column type="expand" fixed="right" label="详情" min-width="120">
              <template #default="props">
                <cj
                    :studentId="currentStudentId"
                    ref="cjRef"/>
              </template>
            </el-table-column>
        </el-table>
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[25, 50, 100, 200]"

            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            style="margin-top: 10px"
        />
      </div>
    </el-tab-pane>
  </el-tabs>
</template>

<style scoped>
.demo-tabs > .el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}

.el-tabs--right .el-tabs__content,
.el-tabs--left .el-tabs__content {
  height: 100%;
}

</style>